<?php
/**
 * Created by PhpStorm.
 * User: sunbo
 * Date: 2019/7/4
 * Time: 6:23 PM
 */
namespace app\index\controller;
use think\Exception;
class Transaction extends CoinBaseContorller
{
    /**
     *
     * @api {post} api/transaction/getListCoin  代币交易
     * @apiDescription  代币交易
     * @apiGroup apptransaction
     * @apiParam {string} coinguid  币guid
     * @apiSuccess {string}  guid   交易内码
     * @apiSuccess {string}  billdatetime  日期
     * @apiSuccess {string}  tokencount 数量
     * @apiSuccess {string}  type 0 转入  1 转出
     * @apiVersion 1.0.1
     */
    public function  getListCoin(){
        $coinguid=$this->param("coinguid");
        $userid=$this->getuserGuid();
        $data=$this->_getListCoin($userid,$coinguid);
        return $this->json_data($data,"");
    }

    function  _getListCoin($userid,$coinguid){
         return  $this->db_select("SELECT guid,billdatetime,tokencount,type from ( select guid,billdatetime,tokencount,type from token_bill_transaction_coin WHERE token_sys_user_guid='".$userid."' and token_sys_coin_guid='".$coinguid."'
UNION ALL
SELECT guid,billdatetime,putin_token_count tokencount,0 type from token_bill_exchange_coin WHERE token_sys_user_guid='".$userid."' and src_token_sys_coin_guid='".$coinguid."') a ORDER BY a.billdatetime desc");
    }


    /**
     *
     * @api {post} api/transaction/get_CoinInfo  代币信息
     * @apiDescription  代币信息
     * @apiGroup apptransaction
     * @apiParam {string} type  type  0 全部  1 只返回代币  2 返回普通币
     * @apiSuccess {string}  guid   币内码
     * @apiSuccess {string}  name  名称
     * @apiSuccess {string}  iscustom  是否代币
     * @apiVersion 1.0.1
     */
    public  function  get_CoinInfo (){
        $type=$this->param("type");
        $row=null;
        switch ($type){
            case "0":
                $row=$this->db_select("SELECT guid,name,iscustom from token_sys_coin");
                break;
            case "1":
                $row=$this->db_select("SELECT guid,name,iscustom from token_sys_coin where iscustom=1");
                break;
            case "2":
                $row=$this->db_select("SELECT guid,name,iscustom from token_sys_coin where iscustom=0");
                break;
        }

        return $this->json_data($row,"");
    }


    /**
     *
     * @api {post} api/transaction/tokencount  兑换-币信息
     * @apiDescription  兑换-币信息
     * @apiGroup apptransaction
     * @apiParam {string} src_coinguid  源币guid
     * @apiParam {string} tar_coinguid  目标币guid
     * @apiSuccess {string}  src_tokencount   原币数量
     * @apiSuccess {string}  tar_tokencount   目标币数量
     * @apiSuccess {string}  fee   手续费
     * @apiSuccess {string}  ratio   比例 1：N
     * @apiVersion 1.0.1
     */
    public function  tokencount(){
         $userid=$this->getuserGuid();
         $src_coinguid=$this->param("src_coinguid");
         $tar_coinguid=$this->param("tar_coinguid");
         $src_tokencount=$this->_tokencount($src_coinguid,$userid)/pow(10,8);
         $tar_tokencount=$this->_tokencount($tar_coinguid,$userid)/pow(10,8);
         $row=$this->db_select("SELECT count(*) counts from token_sys_coin where guid='".$src_coinguid."' and iscustom=1");

         if($row[0]["counts"]>0){
             $feerow=$this->_get_FeeAndRatio($tar_coinguid,$src_coinguid);
         }else{
             $feerow=$this->_get_FeeAndRatio($src_coinguid,$tar_coinguid);
         }
         $fee=$feerow[0]["fee"];
         $ratio=$feerow[0]["ratio"];

         return $this->json_data(array("src_tokencount"=>$src_tokencount,"tar_tokencount"=>$tar_tokencount,"fee"=>$fee*pow(10,2),"ratio"=>$ratio),"");
    }

    function  _tokencount($coinguid,$userid){
        $count=$this->GetCoinCount($coinguid,$userid);
        return $count;
    }

    function _get_FeeAndRatio($src_coin_guid,$tar_coin_guid){
       $ratio= $this->GetRatio();
       return  $this->db_select("SELECT ".$ratio["ratio"]." ratio,fee,".$ratio["id"]." ratio_id from token_sys_coin_exchange_coin WHERE src_token_sys_coin_guid='".$src_coin_guid."' and target_token_sys_coin_guid='".$tar_coin_guid."'");
    }


    /**
     *
     * @api {post} api/transaction/exec_tokencount  兑换-计算数量
     * @apiDescription  兑换-计算数量
     * @apiGroup apptransaction
     * @apiParam {string} src_coin_guid  源币
     * @apiParam {string} tar_coin_guid  目标币
     * @apiParam {string} tokencount  数量
     * @apiSuccess {string}  sum_token_count     总转换数量
     * @apiSuccess {string}  fee_token_count     手续费
     * @apiSuccess {string}  result_token_count     最终转换数量
     * @apiVersion 1.0.1
     */
    public function exec_tokencount()
    {
        $src_coin_guid=$this->param("src_coin_guid");
        $tar_coin_guid=$this->param("tar_coin_guid");
        $tokencount=$this->param("tokencount")*pow(10,8);
        $data=$this->_exec_tokencount($src_coin_guid,$tar_coin_guid,$tokencount);
        $data["sum_token_count"]= round($data["sum_token_count"]/pow(10,8),8);
        $data["fee_token_count"]= round($data["fee_token_count"]/pow(10,8),8);
        $data["result_token_count"]=round($data["result_token_count"]/pow(10,8),8);
        return $this->json_data($data,"");
    }



   public function  _exec_tokencount($src_coin_guid,$tar_coin_guid,$tokencount){
        $row=$this->db_select("SELECT count(*) counts from token_sys_coin where guid='".$src_coin_guid."' and iscustom=1");
        //如果不是代币
        if($row[0]["counts"]==0){
            $row=$this->db_select("SELECT fee from token_sys_coin_exchange_coin WHERE src_token_sys_coin_guid='".$src_coin_guid."' and target_token_sys_coin_guid='".$tar_coin_guid."'");
            $ratiodata=$this->GetRatio();
            $ratio=$ratiodata["ratio"];
            $fee=$row[0]["fee"];
            //属于内扣
            //兑换总数=输入数量*兑换比率
            $sum_token_count=round($tokencount*$ratio,0);
            //手续费数量=兑换总数*手续费
            $fee_token_count=round($sum_token_count*$fee,0);
            //最终数量=兑换总数-手续费数量
            $result_token_count=round($sum_token_count-$fee_token_count,0);

            return  array("sum_token_count"=>$sum_token_count,"fee_token_count"=>$fee_token_count,"result_token_count"=>$result_token_count,"ratio"=>$ratio,"fee"=>$fee*pow(10,2));
        }else{
            $row=$this->db_select("SELECT fee from token_sys_coin_exchange_coin WHERE src_token_sys_coin_guid='".$tar_coin_guid."' and target_token_sys_coin_guid='".$src_coin_guid."'");
            $ratiodata=$this->GetRatio();
            $ratio=$ratiodata["ratio"];
            $fee=$row[0]["fee"];
            //属于内扣
            //手续费数量=输入数量*手续费
            $fee_token_count=round($tokencount*$fee,0);
            //兑换总数=（输入数量-手续费数量)*兑换比率
            $sum_token_count=$tokencount-$fee_token_count;
            //最终数量
            $result_token_count=round($sum_token_count/$ratio,0);
            return  array("sum_token_count"=>$sum_token_count,"fee_token_count"=>$fee_token_count,"result_token_count"=>$result_token_count,"ratio"=>$ratio,"fee"=>$fee*pow(10,2));
        }

    }


    /**
     *
     * @api {post} api/transaction/save_transaction  兑换-提交
     * @apiDescription  兑换-提交
     * @apiGroup apptransaction
     * @apiParam {string} src_coin_guid  源币
     * @apiParam {string} tar_coin_guid  目标币
     * @apiParam {string} tokencount  输入数量
     * @apiSuccess {string}  data   为空表示成功
     * @apiVersion 1.0.1
     */
    public function  save_transaction(){
        try{
            $userid=$this->getuserGuid();
            $src_coin_guid=$this->param("src_coin_guid");
            $tar_coin_guid=$this->param("tar_coin_guid");

            $tokencount=$this->param("tokencount")*pow(10,8);
            $data= $this->check_amount($src_coin_guid,$userid,$tokencount);
            if(strlen($data)>0){
                return $this->json_data("",$data);
            }

            $countlist=$this->_exec_tokencount($src_coin_guid,$tar_coin_guid,$tokencount);
            if($countlist["result_token_count"]==0){
                return $this->json_data("","输入数量太少,无法兑换");
            }
            $data= $this->_save_transaction($src_coin_guid,$tar_coin_guid,$userid,$tokencount,$countlist);
            return $this->json_data($data,"");
        }catch (Exception $e){
            return $this->json_data("",$e->getMessage());
        }
    }

   public  function  check_amount($src_coin_guid,$userid,$tokencount){
       $sum= $this->_tokencount ($src_coin_guid,$userid);
       if($tokencount>$sum){
           return "数量不足";
       }
       return "";
    }

    function  _save_transaction($src_coin_guid,$tar_coin_guid,$userid,$tokencount,$countlist){

        $row=$this->db_select("SELECT count(*) counts from token_sys_coin where guid='".$src_coin_guid."' and iscustom=1");
        $row1=$this->db_select("SELECT count(*) counts from token_sys_coin where guid='".$tar_coin_guid."' and iscustom=1");
        //原单是否是代币
        $src_coinIsCustom=false;
        //目的地单是否是代币
        $tar_coinIsCustom=false;
        //判断目标币是否是代币
        if($row1[0]["counts"]>0){
            $tar_coinIsCustom=true;
        }
        //判断源币是否是代币
        if($row[0]["counts"]==0)
        {
            $feerow=$this->_get_FeeAndRatio($src_coin_guid,$tar_coin_guid);
        }else{
            $feerow=$this->_get_FeeAndRatio($tar_coin_guid,$src_coin_guid);
            $src_coinIsCustom=true;
        }
        $fee=$feerow[0]["fee"];
        $ratio=$feerow[0]["ratio"];
        $ratio_id=$feerow[0]["ratio_id"];
        $sql=" INSERT INTO token_bill_exchange_coin (guid,billdate,billdatetime,token_sys_user_guid,src_token_sys_coin_guid,target_token_sys_coin_guid,
 putin_token_count,fee,result_token_count,fee_token_count,sum_token_count,ratio,token_sys_ratio_id) 
 VALUES(UUID(),'".date("Y-m-d")."','".date("Y-m-d H:i:s")."','".$userid."','".$src_coin_guid."','".$tar_coin_guid."',".$tokencount.",".$fee.",".$countlist["result_token_count"].",".$countlist["fee_token_count"].",".$countlist["sum_token_count"].",".$ratio.",'".$ratio_id."')";
       $array=array("$sql");
        //扣手续费
        $array[]="update token_user_custom_coin_balance set token_count=token_count-".$fee." WHERE token_sys_user_guid='".$userid."'";
        //如果是原币相等于转出
        if($src_coinIsCustom){
            $array[]="update token_user_custom_coin_balance set token_count=token_count-".$tokencount." WHERE token_sys_user_guid='".$userid."'";
        }

        //如果是目标币相当于转入
        if($tar_coinIsCustom){
            $array[]="update token_user_custom_coin_balance set token_count=token_count+".$countlist["result_token_count"]." WHERE token_sys_user_guid='".$userid."'";
        }
        return $this->db_exec($array);
    }

    /**
     *
     * @api {post} api/transaction/Get_Address  转入-获取地址
     * @apiDescription  转入-获取地址
     * @apiGroup apptransaction
     * @apiParam {string} coin_guid  源币
     * @apiSuccess {string}  data   地址
     * @apiVersion 1.0.1
     */
    public function Get_Address(){
        try{
            $userid=$this->getuserGuid();
            $coin_guid=$this->param("coin_guid");
            $address= $this->GetAddressFromUserAndCoinGuid($userid,$coin_guid);
            return $this->json_data($address,"");
        }catch (Exception $e){
            return $this->json_data("",$e->getMessage());
        }

    }
}